<template>
  <div class="bg-white rounded-lg shadow-md p-6">
    <h2 class="text-xl font-semibold text-gray-800 mb-6">安全设置</h2>

    <el-form
      ref="securityForm"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="max-w-lg"
    >
      <!-- 当前密码 -->
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input
          v-model="formData.currentPassword"
          type="password"
          placeholder="请输入当前密码"
          show-password
        />
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item label="验证码" prop="code" v-if="showCodeField">
        <div class="flex items-center gap-2">
          <el-input
            v-model="formData.code"
            placeholder="请输入6位验证码"
            maxlength="6"
            @input="formData.code = formData.code.replace(/[^\d]/g, '')"
          />
          <el-button
            type="primary"
            :disabled="cooldown > 0"
            @click="sendVerificationCode"
            class="w-32"
          >
            {{ cooldown > 0 ? `${cooldown}秒后重发` : '获取验证码' }}
          </el-button>
        </div>
      </el-form-item>

      <!-- 新密码 -->
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="formData.newPassword"
          type="password"
          placeholder="请输入新密码"
          show-password
        />
      </el-form-item>

      <!-- 确认新密码 -->
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input
          v-model="formData.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          show-password
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm"
          :loading="submitting"
        >
          确认修改
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../store'

const userStore = useUserStore()
const securityForm = ref(null)
const cooldown = ref(0)
const submitting = ref(false)
const showCodeField = ref(false)
let cooldownTimer = null

const formData = reactive({
  currentPassword: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码必须为6位数字', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

function validateConfirmPassword(rule, value, callback) {
  if (value !== formData.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

function sendVerificationCode() {
  if (cooldown.value > 0) return
  
  // 先验证当前密码
  securityForm.value.validateField('currentPassword', (valid) => {
    if (valid) {
      userStore.sendSecurityCode().then(() => {
        startCooldown()
        showCodeField.value = true
      })
    }
  })
}

function startCooldown() {
  cooldown.value = 60
  cooldownTimer = setInterval(() => {
    cooldown.value--
    if (cooldown.value <= 0) {
      clearInterval(cooldownTimer)
    }
  }, 1000)
}

function submitForm() {
  securityForm.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      await userStore.changePassword(
        formData.currentPassword,
        formData.newPassword,
        formData.code
      )
      ElMessage.success('密码修改成功')
      // 清空表单
      securityForm.value.resetFields()
      showCodeField.value = false
    } catch (error) {
      ElMessage.error(error.message || '密码修改失败')
    } finally {
      submitting.value = false
    }
  })
}

onBeforeUnmount(() => {
  if (cooldownTimer) {
    clearInterval(cooldownTimer)
  }
})
</script>